package com.zxt.content.user.security;

import com.zxt.bean.UserInfoVO;
import com.zxt.user.resp.LoginUserVO;
import com.zxt.content.user.manager.BUserManager;
import com.zxt.content.user.model.BUser;
import com.zxt.utils.ZXTBeanUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * 用户验证处理
 */
@Service
@Slf4j
@AllArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {

    private final BUserManager bUserManager;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        BUser user = bUserManager.getByUserName(username);
        if (Objects.isNull(user)) {
            // 用户不存在
            throw new UsernameNotFoundException("用户不存在");
        }
        return createLoginUser(user);
    }

    public UserDetails createLoginUser(BUser user) {
        return new LoginUserVO(ZXTBeanUtils.beanCopy(user, UserInfoVO.class));
    }
}
